var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');

require('superagent-proxy')(superagent);

var mysqlCloudMusic = require('./config').mysqlCloudMusic;
var mysqlProxy = require('./config').mysqlProxy;

function main(options) {
    const offset = options.offset;

    var ipList = [];
    var ipIndex = 0;
    var proxy = '';

    var song;
    var commentList = [];
    var commentCount;

    function changeIp() {
        if (ipIndex < ipList.length - 1) {
            ipIndex += 1;
        } else {
            ipIndex = 0;
        }
        setProxy();
    }

    function setProxy() {
        var item = ipList[ipIndex];
        var ip = item.ip;
        var port = item.port;

        proxy = `http://${ip}:${port}`;
        console.log(proxy);
        console.log();
    }

    getIpList();
    function getIpList() {
        var connection1 = mysql.createConnection(mysqlProxy);
        var query1 = 'select * from ip_table1 where success_count>5 order by success_count desc limit 1000 ';
        connection1.connect();
        connection1.query(query1, function (err, res) {
            if (err) {
                console.log(err);

            } else {
                ipList = res;
                setProxy();
                setInterval(() => {
                    changeIp();
                }, 300 * 1000);
                getSong();
            }
        });
        connection1.end();
    }

    function getSong() {
        var query2 = `SELECT * FROM song ORDER BY comment_version LIMIT 1 offset ${offset};`
        var connection2 = mysql.createConnection(mysqlCloudMusic);
        connection2.connect();
        connection2.query(query2, function (err2, res2) {
            if (err2) {
                console.log(err2);
            } else {
                console.log(res2);
                console.log();

                if (res2.length === 0) {
                    setTimeout(() => {
                        getSong();
                    }, 3600 * 1000);
                } else {
                    song = res2[0];
                    console.log(song);

                    getComment();
                }
            }
        });
        connection2.end();
    }

    function getComment() {
        console.log(song);

        const songId = song.id;
        let url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_' + songId;
        superagent.get(url)
            .timeout(3000)
            // .proxy(proxy)
            .end(function (err3, res3) {
                console.log(url);
                
                if (err3) {
                    console.log(err3);
                    setTimeout(() => {
                        changeIp();
                        getComment();
                    }, 2000);
                } else {
                    let text = res3.text;
                    fs.writeFile('html/comment.json', text, function () {
                        // 
                    });
                    if (/Cheating/g.test(text)) {
                        setTimeout(() => {
                            changeIp();
                            getComment();
                        }, 2000);
                    } else if (/资源不存在/g.test(text)) {
                        feedback();
                    } else {
                        let o = {};
                        try {
                            o = JSON.parse(res3.text);
                        } catch (error) {
                            console.log(error);
                        }
                        // console.log(o);

                        var hotComments = o.hotComments;
                        if (typeof hotComments !== 'undefined') {
                            commentCount = o.total;

                            if (hotComments.length > 0) {
                                commentList = o.hotComments.map(v => {
                                    var id = v.commentId;
                                    var content = v.content;
                                    var time = v.time;
                                    var likedCount = v.likedCount;
                                    return [id, content, time, likedCount, songId];
                                });
                                upload();
                            } else {
                                console.log('没有热门评论');
                                console.log();
                                feedback();
                            }
                        } else {
                            console.log(o);

                        }
                    }
                }
            })
    }

    function upload() {
        var queryString = 'replace into comment (id,content,time,liked_count,song_id) values ?';

        var connection = mysql.createConnection(mysqlCloudMusic);
        connection.connect();
        connection.query(queryString, [commentList], function (err, res) {
            if (err) {
                console.log(err);
            } else {
                console.log(res);
                feedback();
            }
        });
        connection.end();
    }

    function feedback() {
        const songId = song.id;
        let commentVersion = song.comment_version;
        if (commentVersion) {
            commentVersion += 1;
        } else {
            commentVersion = 1;
        }

        var query4 = `update song set comment_version=${commentVersion},comment_count=${commentCount} where id=${songId}`;
        console.log(query4);

        var connection4 = mysql.createConnection(mysqlCloudMusic);
        connection4.connect();
        connection4.query(query4, function (err, res) {
            if (err) {
                console.log(err);

            } else {
                console.log(res);
                setTimeout(() => {
                    getSong();
                }, 2000);
            }
        });
        connection4.end();
    }
}

for (var i = 0; i < 1; i++) {
    main({
        offset: 10 * i
    });
}